package com.scm.biz.service._impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.itextpdf.text.log.SysoCounter;
import com.scm.biz.bean.DesignOrder;
import com.scm.biz.bean.Order;
import com.scm.biz.bean.OrderTaskPerformer;
import com.scm.biz.bean.ProductionOrder;
import com.scm.biz.bean.ProductionPattern;
import com.scm.biz.bean.ProductionPatternSize;
import com.scm.biz.bean.SysUser;
import com.scm.biz.dao.CustomerDao;
import com.scm.biz.dao.DesignOrderDao;
import com.scm.biz.dao.OrderDao;
import com.scm.biz.dao.OrderTaskPerformerDao;
import com.scm.biz.dao.ProductionOrderDao;
import com.scm.biz.dao.ProductionPatternDao;
import com.scm.biz.dao.ProductionPatternSizeDao;
import com.scm.biz.dto.MsgNoticeDto;
import com.scm.biz.dto.ProductionOrderDto;
import com.scm.biz.enums.FileCategoryEnum;
import com.scm.biz.enums.OrderStatusEnum;
import com.scm.biz.enums.OrderTypeEnum;
import com.scm.biz.query.ProductionOrderQuery;
import com.scm.biz.result.ProductionOrderResult;
import com.scm.biz.service.BusinessFileService;
import com.scm.biz.service.MsgNoticeService;
import com.scm.biz.service.OrderTaskFlowService;
import com.scm.biz.service.OrderTaskPerformerService;
import com.scm.biz.service.ProductionOrderService;
import com.scm.biz.service.ProductionPatternService;
import com.scm.core.bean.exp.UfdmException;
import com.scm.utils.UfdmDateUtil;

@Service
public class ProductionOrderServiceImpl implements ProductionOrderService {

	@Autowired
	ProductionOrderDao productionOrderDao;
	@Resource
	ProductionPatternService productionPatternService;
	@Autowired
	ProductionPatternDao productionPatternDao;
	@Autowired
	ProductionPatternSizeDao productionPatternSizeDao;
	@Autowired
	BusinessFileService businessFileService;
	@Autowired
	OrderTaskFlowService orderTaskFlowService;
	@Autowired
	OrderDao orderDao;
	@Autowired
	CustomerDao customerDao;
	@Autowired
	MsgNoticeService msgNoticeService;
	@Autowired
	DesignOrderDao designOrderDao;
	@Autowired
	OrderTaskPerformerService orderTaskPerformerService;
	@ResponseBody
	@Override
	public void insert(ProductionOrderDto productionOrderDto, MultipartFile file) throws UfdmException {
		ProductionOrder productionOrder = new ProductionOrder();
		productionOrder.setOrderId(productionOrderDto.getOrderId());
		productionOrder.setCreateAt(new Date());
		productionOrder.setEnddate(UfdmDateUtil.stringToDate(
				productionOrderDto.getEnddate(), "yyyy-MM-dd"));
		productionOrder.setRequirement(productionOrderDto.getRequirement());
		Integer userId = Integer.valueOf(SecurityUtils.getSubject().getSession().getAttribute("userId").toString());
		productionOrder.setCreator(userId);
		productionOrderDao.insert(productionOrder);
		businessFileService.insert(file, productionOrder.getId(), FileCategoryEnum.PRODUCTION_CONTACT_SALE_FILE.value(), 0);
		Map<String, List<ProductionPatternSize>> orderPatternIdMap = new HashMap<String, List<ProductionPatternSize>>();
		ProductionPatternSize productionPatternSize = null;
		for (Map<String, Object> data : productionOrderDto.getPatternSizeList()) {
			productionPatternSize = new ProductionPatternSize();
			if (data.get("color") != null) {
				productionPatternSize.setColor(data.get("color").toString());
			}
			if (data.get("lAmount") != null
					&& !data.get("lAmount").toString().isEmpty()) {
				productionPatternSize.setlAmount(Integer.valueOf(data.get(
						"lAmount").toString()));
			}
			if (data.get("mAmount") != null
					&& !data.get("mAmount").toString().isEmpty()) {
				productionPatternSize.setlAmount(Integer.valueOf(data.get(
						"mAmount").toString()));
			}

			if (data.get("sAmount") != null
					&& !data.get("sAmount").toString().isEmpty()) {
				productionPatternSize.setsAmount(Integer.valueOf(data.get(
						"sAmount").toString()));
			}
			if (data.get("xlAmount") != null
					&& !data.get("xlAmount").toString().isEmpty()) {
				productionPatternSize.setXlAmount(Integer.valueOf(data.get(
						"xlAmount").toString()));
			}
			if (data.get("xsAmount") != null
					&& !data.get("xsAmount").toString().isEmpty()) {
				productionPatternSize.setXsAmount(Integer.valueOf(data.get(
						"xsAmount").toString()));
			}
			if (data.get("xxlAmount") != null
					&& !data.get("xxlAmount").toString().isEmpty()) {
				productionPatternSize.setXxlAmount(Integer.valueOf(data.get(
						"xxlAmount").toString()));
			}
			if (!orderPatternIdMap.containsKey(data.get("orderPatternId")
					.toString())) {
				orderPatternIdMap.put(data.get("orderPatternId").toString(),
						new ArrayList<ProductionPatternSize>());
			}
			orderPatternIdMap.get(data.get("orderPatternId").toString()).add(
					productionPatternSize);
		}
		Integer manager = orderDao.selectByPrimaryKey(productionOrderDto.getOrderId()).getManager();
		if(manager==null){
			throw new UfdmException("该订单不存在项目经理,请先指定项目经理");
		}
		for (Entry<String, List<ProductionPatternSize>> entry : orderPatternIdMap
				.entrySet()) {

			ProductionPattern productionPattern = new ProductionPattern();
			productionPattern.setOrderPatternId(Long.valueOf(entry.getKey()));
			productionPattern.setProductionOrderId(productionOrder.getId());
			productionPattern.setStatus(OrderStatusEnum.PRODUCTION_CREATED.value());
			
			productionPatternDao.insert(productionPattern);
			
			OrderTaskPerformer orderTaskPerformer = new OrderTaskPerformer();
			orderTaskPerformer.setAction("F205");
			orderTaskPerformer.setBusinessId(productionPattern.getId());
			orderTaskPerformer.setBusinessType(OrderTypeEnum.T3.toString());
			orderTaskPerformer.setCreatedAt(new Date());
			orderTaskPerformer.setPerformer(userId);
			orderTaskPerformer.setUpdatedAt(new Date());
			orderTaskPerformer.setOrderId(productionOrderDto.getOrderId());
			orderTaskPerformerService.addPerformer(orderTaskPerformer);
			
			
			orderTaskFlowService.addPerformer(OrderTypeEnum.T3, "F300", manager, productionPattern.getId());
			for (ProductionPatternSize _productionPatternSize : entry.getValue()) {
				_productionPatternSize.setProductionPatternId(productionPattern
						.getId());
				productionPatternSizeDao.insert(_productionPatternSize);
			}
		}
		
		/********************消息***************/
		Order order = orderDao.selectByPrimaryKey(productionOrder.getOrderId());
		MsgNoticeDto msgNoticeDto = new MsgNoticeDto();
		msgNoticeDto.setTitle("样衣已通过选款");
		msgNoticeDto.setContent(customerDao.selectByPrimaryKey(order.getCustomerId().intValue()).getFullname()
								+ "客户的样衣已通过选稿，进入大货流程");
		msgNoticeDto.setOrderType(OrderTypeEnum.T3.toString());                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
		msgNoticeDto.setTaskId(productionOrder.getId());
		msgNoticeDto.setUserType(0);
		msgNoticeDto.setOrderId(order.getId());
		msgNoticeService.insert(msgNoticeDto,order.getManager());
		DesignOrder designOrder = designOrderDao.selectByOrderId(productionOrder.getOrderId());
		if(designOrder !=null){
			msgNoticeService.insert(msgNoticeDto,designOrder.getDesigner());
		}
		
		
		SysUser sysUser = (SysUser)SecurityUtils.getSubject().getSession().getAttribute("sysUser");
		
		msgNoticeDto.setTitle("新的大货订单");
		System.out.println(sysUser+"################################");
		msgNoticeDto.setContent(sysUser.getName()+"创建了"+customerDao.selectByPrimaryKey(order.getCustomerId().intValue()).getFullname()
								+ "客户的大货订单，请尽快安排工厂，截止时间为"+UfdmDateUtil.dateToString(productionOrder.getEnddate(), "MM月dd日"));
		msgNoticeService.insert(msgNoticeDto,order.getManager());
		
	}

	@Override
	public void update(ProductionOrder productionOrder) {
		productionOrderDao.updateByPrimaryKey(productionOrder);
	}

	@Override
	public List<ProductionOrderResult> selectPage(
			ProductionOrderQuery productionOrderQuery) {
		return productionOrderDao.selectPage(productionOrderQuery);
	}

	@Override
	public ProductionOrderResult selectById(Long id) {
		return productionOrderDao.selectById(id);
	}

	@Override
	public int selectTotal(ProductionOrderQuery productionOrderQuery) {
		return productionOrderDao.selectTotal(productionOrderQuery);
	}

	@Override
	public ProductionOrder selectByPk(Long id) {
		return productionOrderDao.selectByPrimaryKey(id);
	}

}
